import "dart:developer";

import 'package:dio/dio.dart';
import "package:get/get.dart" as GetX;
import 'package:ball_lion/entity/home/user_page_sub_entity.dart';
import 'package:ball_lion/entity/my/help/feedback_entity.dart';
import 'package:ball_lion/entity/my/help/help_entity.dart';
import 'package:ball_lion/entity/my/my_system_msg_entity.dart';
import 'package:ball_lion/entity/my/my_collection_entity.dart';
import 'package:ball_lion/entity/my/my_focus_entity.dart';
import 'package:ball_lion/entity/my/team_focus_entity.dart';
import 'package:ball_lion/entity/other/auth_entity.dart';
import 'package:ball_lion/entity/other/user_info_entity.dart';
import 'package:ball_lion/server/http/dio_utils.dart';
import 'package:ball_lion/utils/local_read_history.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/entity/my/my_interact_entity.dart';

import 'package:ball_lion/entity/other/third_auth_entity.dart';
import 'package:ball_lion/entity/record/recent_channel_entity.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import '../api_dir.dart';

typedef FResponse = Future<Response<dynamic>>;

class UserApi {
  ///发送验证码
  static Future<int?> sendSms(String phone, int code) async {
    final params = {"code": code, "phone": phone};
    final result =
        await DioUtils.post("/resource/rse-sms-do/sendCode", params: params);
    if (result.statusCode == 200) {
      return result.data["c"];
    }
    return null;
  }

  ///二次验证
  static Future<int?> loginSafetyValidate(String code, String key) async {
    final params = {"key": key, "code": code};
    final result =
        await DioUtils.post("/resource/app-do/kaptchaValidate", params: params);
    if (result.statusCode == 200) {
      return result.data["c"];
    }
    return null;
  }

  ///游客登录
  static Future<AuthEntity?> guestLogin(String uuid) async {
    final params = {
      "uuid": uuid,
    };
    final result = await DioUtils.post("/${ApiDir.user}/usr-do/visitorLogin",
        params: params);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return AuthEntity.fromJson(result.data["d"]);
    }
    return null;
  }

  ///登录
  //accessCode 二次登陆用
  //channel 渠道
  //version 版本号
  //token 一键登录token
  static Future<AuthEntity?> login(
      {String? phone,
      String? smsCode,
      String? accessCode,
      String? channel,
      String? version,
      String? token}) async {
    final params = {
      "phone": phone,
      "smsCode": smsCode ?? "",
      "accessCode": accessCode ?? "",
      "channel": channel ?? "",
      "version": version ?? "",
      "tokenCode": token ?? ""
    };
    final result =
        await DioUtils.post("/${ApiDir.user}/usr-do/login", params: params);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return AuthEntity.fromJson(result.data["d"]);
    }
    return null;
  }

  ///绑定手机
  static Future<AuthEntity?> bindPhone(
      {String? phone,
      String? userId,
      String? smsCode,
      String? tokenCode}) async {
    final params = {
      "phone": phone,
      "smsCode": smsCode ?? "",
      "userId": userId ?? "",
      "tokenCode": tokenCode ?? ""
    };
    final result =
        await DioUtils.post("/${ApiDir.user}/usr-do/bindPhone", params: params);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return AuthEntity.fromJson(result.data["d"]);
    }
    return null;
  }

  ///三方登录
  static Future<AuthEntity?> thirdLogin(
      {String? qqAccessToken,
      String? qqOpenid,
      String? wbAccessToken,
      String? wbUid,
      String? iosIdentityToken,
      String? wxCode}) async {
    final params = {
      "qqAccessToken": qqAccessToken,
      "qqOpenid": qqOpenid,
      "wbAccessToken": wbAccessToken,
      "wbUid": wbUid,
      "iosIdentityToken": iosIdentityToken,
      "wxCode": wxCode,
    };
    final result = await DioUtils.post("/${ApiDir.user}/app-auth/authLogin",
        params: params, showLoading: true);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return AuthEntity.fromJson(result.data["d"]);
    }
    return null;
  }

  ///邀请人
  static Future<int?> myInviter(String code) async {
    final params = {"channel": code};
    final result = await DioUtils.post(
        "/${ApiDir.user}/usr-do/channelPromotionAdd",
        params: params);
    if (result.statusCode == 200) {
      return result.data["c"];
    }
    return null;
  }

  static Future<bool?> nameUpdate(String name) async =>
      await Utils.tryOrNullf(() async {
        final response = await DioUtils.post(
            "/${ApiDir.user}/usr-do/nameUpdate",
            params: {"name": name, "userId": User.auth?.userId ?? ""},
            showLoading: true,
            showToast: false);
        final r = response.data["m"];
        if (r == "成功") {
          if (response.data["t"] != null) {
            Toast.text(response.data["t"].toString());
          }
          return true;
        } else if (r == "距离上次修改未达到时间") {
          if (User.info?.isVip == 1) {
            Toast.text("会员仅支持3天内修改1次哦");
          } else {
            bool result = await GetX.Get.dialog(const QsDialog.alert(
                "90天内支持修改一次昵称。如需继续修改，请开通会员",
                confirmText: "开通会员",
                cancelText: "知道了"));
            if (result == true) {
              GetX.Get.toNamed(Routes.vipCenter);
            }
          }
        } else {
          Toast.text(r);
        }
        return false;
      });

  static syncNewsRead() {
    final list = LocalReadHistory.readedNews();
    if (list.isEmpty) {
      return;
    }
    DioUtils.post("/${ApiDir.info}/info-news-comment-do/news/read",
        params: {"idList": list});
  }

  ///获取足球关注列表
  ///type 1 为足球  type 2 为篮球
  static Future<Response> getMatchFocusList({int type = 1}) async {
    return await DioUtils.post("/${ApiDir.user}/usr-do/matchFocusList",
        params: {"type": type, "userId": User.auth?.userId ?? ""});
  }

  static Future<Response> getBasketballMatchFocusList() =>
      getMatchFocusList(type: 2);

  ///增加或删除足球关注
  static Future<bool> makeMatchFocusUpdate(List<int> ids, bool isFocus,
          {int type = 1}) async =>
      await Utils.tryOrNullf(() async {
        final response = await DioUtils.post(
            "/${ApiDir.user}/usr-do/matchFocusUpdate",
            params: {
              "type": type,
              "userId": User.auth?.userId ?? "",
              "addOrDel": isFocus ? 1 : 2,
              "list": ids
            });
        return response.data["d"] ?? false;
      }) ??
      false;

  static Future<bool> makeBasketballMatchFocusUpdate(
          List<int> ids, bool isFocus) =>
      makeMatchFocusUpdate(ids, isFocus, type: 2);

  ///账户注销
  static Future<int?> cancelAccount() async {
    final result = await DioUtils.post("/${ApiDir.user}/usr-do/cancel");
    if (result.statusCode == 200) {
      return result.data["c"];
    }
    return null;
  }

  static Future<UserInfoEntity?> getUserInfo() async =>
      await Utils.tryOrNullf(() async {
        final response = await DioUtils.post("/${ApiDir.user}/usr-do/userInfo",
            params: {"id": SpUtils.loginAuth?.userId ?? ""});
        return UserInfoEntity.fromJson(response.data["d"]);
      });

  //获取关注球队列表
  static Future<List<TeamFocusEntity>> getTeamFocusList({int? sportsId}) async {
    try {
      final r = await DioUtils.post("/user/usr-team-focus-do/myTeamFocusList",
          params: {"id": sportsId});
      final l = r.data['d'] as List;
      return l.map((e) => TeamFocusEntity.fromJson(e)).toList();
    } catch (err) {}
    return [];
  }

  //获取关注联赛列表
  static Future<List<RecentChannelEntity>> getChannelFocusList(
      {int? sportsId}) async {
    try {
      final r = await DioUtils.post("/${ApiDir.user}/usr-league-focus-do/my",
          params: {"id": sportsId});
      final l = r.data['d'] as List;
      return l.map((e) => RecentChannelEntity.fromFocus(e)).toList();
    } catch (err) {
      log(err.toString());
      return [];
    }
  }

  ///修改头像
  static Future<int?> avatarUpdate(String avatar,
      {bool showLoading = false}) async {
    final params = {"avatar": avatar, "userId": User.auth?.userId};
    final result = await DioUtils.post("/${ApiDir.user}/usr-do/avatarUpdate",
        params: params, showLoading: showLoading);
    if (result.statusCode == 200) {
      return result.data["c"];
    }
    return null;
  }

  //获取系统头像
  static Future<List<String>?> getSystemAvatar() async {
    final result = await DioUtils.post("/${ApiDir.user}/usr-do/avatarList");
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return result.data["d"].cast<String>();
    }
    return null;
  }

  //实名认证
  static Future<Response> authCheckName(
          String cardID, String name, String code) =>
      DioUtils.post("/${ApiDir.user}/app-auth/checkName",
          showLoading: true,
          params: {"cardNo": cardID, "name": name, "smsCode": code});

  //批量关注
  static Future<int?> batchFocus(List<String>? expertId) async {
    final result = await DioUtils.post(
        "/${ApiDir.user}/app-user-focus/batchBind",
        params: {"expertId": expertId});
    if (result.data != null) {
      if (result.data["c"] == 200) {
        Toast.text('关注成功');
      }
      return result.data["c"];
    }
    return null;
  }

  //关注
  static Future<int?> focus({String? userId, String? expertId}) async {
    final params = {"userId": userId, "expertId": expertId};
    final result = await DioUtils.post("/${ApiDir.user}/app-user-focus/bind",
        params: params);
    if (result.data != null) {
      return result.data["c"];
    }
    return null;
  }

  //取消关注
  static Future<int?> unFocus({String? userId, String? expertId}) async {
    final params = {"userId": userId, "expertId": expertId};
    final result = await DioUtils.post("/${ApiDir.user}/app-user-focus/unbind",
        params: params);
    if (result.data != null) {
      return result.data["c"];
    }
    return null;
  }

  ///关注球队
  static Future<int?> focusTeam(int? id, int? sportsId) async {
    final data = {
      "addOrDel": 1,
      "list": [id],
      "sportsId": sportsId,
      'userId': User.auth?.userId,
    };
    final result = await DioUtils.post(
        "/${ApiDir.user}/usr-team-focus-do/teamFocusUpdate",
        params: data);
    if (result.statusCode == 200) {
      return result.data['c'];
    }
    return null;
  }

  ///取消关注球队
  static Future<int?> unFocusTeam(int? id, int? sportsId) async {
    final data = {
      "addOrDel": 2,
      "list": [id],
      "sportsId": sportsId,
      'userId': User.auth?.userId,
    };
    final result = await DioUtils.post(
        "/${ApiDir.user}/usr-team-focus-do/teamFocusUpdate",
        params: data);
    if (result.statusCode == 200) {
      return result.data['c'];
    }
    return null;
  }

  ///关注球队
  static Future<int?> updateFocusTeam(List<int>? ids, int? sportsId) async {
    final data = {
      "addOrDel": 3,
      "list": ids,
      "sportsId": sportsId,
      'userId': User.auth?.userId,
    };
    final result = await DioUtils.post(
        "/${ApiDir.user}/usr-team-focus-do/teamFocusUpdate",
        params: data);
    if (result.statusCode == 200) {
      return result.data['c'];
    }
    return null;
  }

  //关注联赛
  static Future<int?> focusChannel(int? leagueId, int? sportsId) async {
    final data = {"leagueId": leagueId, "sportsId": sportsId};
    final result = await DioUtils.post(
        "/${ApiDir.user}/usr-league-focus-do/bind",
        params: data);
    if (result.data != null) {
      return result.data['c'];
    }
    return null;
  }

  //取消关注联赛
  static Future<int?> unFocusChannel(int? leagueId, int? sportsId) async {
    final data = {"leagueId": leagueId, "sportsId": sportsId};
    final result = await DioUtils.post(
        "/${ApiDir.user}/usr-league-focus-do/unbind",
        params: data);
    if (result.data != null) {
      return result.data['c'];
    }
    return null;
  }

  //关注联赛更改顺序
  static Future<int?> updateFocusChannel(
      List<int>? leagueIds, int? sportsId) async {
    final data = {"ids": leagueIds, "sportsId": sportsId};
    final result = await DioUtils.post(
        "/${ApiDir.user}/usr-league-focus-do/updateFocusForUserId",
        params: data);
    if (result.data != null) {
      return result.data['c'];
    }
    return null;
  }

  static Future<List<MyCollectionEntity>?> getMyCollection(
      int type, int page, int pageSize) async {
    final params = {
      "data": {"type": type},
      "page": page,
      "pageSize": pageSize
    };
    final result = await DioUtils.post("/${ApiDir.info}/info-collect-do/list",
        params: params);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      List<MyCollectionEntity> data = result.data["d"]
          .map<MyCollectionEntity>((e) => MyCollectionEntity.fromJson(e))
          .toList();
      return data;
    }
    return null;
  }

  //收藏
  //type 1文章 2帖子 3视频
  static Future<int?> collect(int type, int id) async {
    final params = {
      "href": {
        "id": id,
        "params": {
          "path": type == 3 ? Routes.homeVideoNews : Routes.homenews,
          "arguments": id
        }
      },
      "type": type
    };
    final result = await DioUtils.post("/${ApiDir.info}/info-collect-do/add",
        params: params);
    if (result.data != null) {
      return result.data["c"];
    }
    return null;
  }

  //收藏
  //type 1文章 2帖子 3视频
  static Future<int?> deleteCollect(int id) async {
    final params = {"id": id};
    final result = await DioUtils.post(
        "/${ApiDir.info}/info-collect-do/deleteByNewsId",
        params: params);
    if (result.data != null) {
      return result.data["c"];
    }
    return null;
  }

  //用户主页订阅情况
  static Future<UserPageSubEntity?> getUserPageSub(String id) async {
    final params = {
      "expertId": id,
    };
    final result = await DioUtils.post("/${ApiDir.plan}/app-idea/userSubs",
        params: params);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      UserPageSubEntity data = UserPageSubEntity.fromJson(result.data["d"]);
      return data;
    }
    return null;
  }

  ///专家关注列表
  static Future<List<MyFocusEntity>?> myFocusUser(
      int page, int pageSize) async {
    final params = {"page": page, "pageSize": pageSize};
    final result = await DioUtils.post("/${ApiDir.user}/app-user-focus/my",
        params: params);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      List<MyFocusEntity> d = result.data["d"]["rows"]
          .map<MyFocusEntity>((e) => MyFocusEntity.fromJson(e)..isFocus = 1)
          .toList();
      return d;
    }
    return null;
  }

  //发帖
  static Future<int?> publishPost(String images, String content) async {
    final params = {"content": content, "imgs": images};
    final result = await DioUtils.post(
        "/${ApiDir.info}/app-publish-do/publishPost",
        params: params,
        showLoading: true);
    if (result.data != null) {
      return result.data["c"];
    }
    return null;
  }

  //删帖
  static Future<int?> deletePost(int id) async {
    final params = {"id": id};
    final result = await DioUtils.post(
        "/${ApiDir.info}/app-publish-do/deletePost",
        params: params,
        showLoading: true);
    if (result.data != null) {
      return result.data["c"];
    }
    return null;
  }

  //系统通知未读
  static Future<int?> getSystemUnreadCount() async {
    try {
      final result =
          await DioUtils.post("/${ApiDir.info}/info-user-letter-do/readCount");
      if (result.statusCode == 200 && result.data["c"] == 200) {
        return result.data["d"];
      }
    } catch (e) {}
    return null;
  }

  //系统通知列表
  static Future<List<MySystemMsgEntity>?> getSystemMsg(
      {int page = 1, int size = 20}) async {
    try {
      final result = await DioUtils.post(
          "/${ApiDir.info}/info-user-letter-do/list",
          params: {"page": page, "pageSize": size});
      if (result.statusCode == 200 && result.data["c"] == 200) {
        List rows = result.data["d"]["rows"];
        return rows.map((e) => MySystemMsgEntity.fromJson(e)).toList();
      }
    } catch (err) {}
    return null;
  }

  //已读系统通知
  static Future<int?> readSystemMsg(int id) async {
    try {
      final result = await DioUtils.post(
          "/${ApiDir.info}/info-user-letter-do/add",
          params: {"id": id});
      if (result.statusCode == 200) {
        return result.data["c"];
      }
    } catch (e) {}
    return null;
  }

  //未读互动
  static Future<int?> getInterUnreadCount() async {
    try {
      final result = await DioUtils.post(
          "/${ApiDir.info}/info-user-interaction-do/readCount");
      if (result.statusCode == 200 && result.data["c"] == 200) {
        return result.data["d"];
      }
    } catch (e) {}
    return null;
  }

  //互动列表
  static Future<List<MyInteractEntity>?> getInteract(
      {int page = 1, int size = 20}) async {
    try {
      final result = await DioUtils.post(
          "/${ApiDir.info}/info-user-interaction-do/list",
          params: {"page": page, "pageSize": size});
      if (result.statusCode == 200 && result.data["c"] == 200) {
        List rows = result.data["d"]["rows"];
        return rows.map((e) => MyInteractEntity.fromJson(e)).toList();
      }
    } catch (err) {}
    return null;
  }

  //互动已读
  static Future<int?> readInteract(int id) async {
    try {
      final result = await DioUtils.post(
          "/${ApiDir.info}/info-user-interaction-do/add",
          params: {"id": id});
      if (result.statusCode == 200) {
        return result.data["c"];
      }
    } catch (e) {}
    return null;
  }

  //邀请好友
  static Future<Response> joinActivity(String activityId,
      {bool needLoading = false}) async {
    final params = {
      "activityId": activityId,
    };
    final result = await DioUtils.post(
        "/${ApiDir.user}/usr-coupon-do/joinActivity",
        params: params,
        showLoading: needLoading);

    return result;
  }

  ///三方绑定
  static Future<int?> thirdBind(
      {String? qqAccessToken,
      String? qqOpenid,
      String? wbAccessToken,
      String? wbUid,
      String? iosIdentityToken,
      String? wxCode}) async {
    final params = {
      "qqAccessToken": qqAccessToken,
      "qqOpenid": qqOpenid,
      "wbAccessToken": wbAccessToken,
      "wbUid": wbUid,
      "iosIdentityToken": iosIdentityToken,
      "wxCode": wxCode,
    };
    final result = await DioUtils.post("/${ApiDir.user}/app-auth/authBind",
        params: params, showLoading: true);
    if (result.statusCode == 200) {
      return result.data["c"];
    }
    return null;
  }

  ///三方解绑
  static Future<int?> thirdUnbind(int type) async {
    final result = await DioUtils.post("/${ApiDir.user}/app-auth/authUnBind",
        params: type, showLoading: true);
    if (result.statusCode == 200) {
      return result.data["c"];
    }
    return null;
  }

  ///获取绑定信息
  static Future<List<ThirdAuthEntity>?> getAuthList() async {
    final result = await DioUtils.post("/${ApiDir.user}/app-auth/authList",
        showLoading: true);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return result.data["d"]
          .map<ThirdAuthEntity>((e) => ThirdAuthEntity.fromJson(e))
          .toList();
    }
    return null;
  }

  ///获取问题列表
  static Future<List<QuestionEntity>> getQuestions(int id) async {
    final result = await DioUtils.post(
        "/${ApiDir.info}/app-help-suggest/helpList",
        params: id);
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return result.data["d"]
          .map<QuestionEntity>((e) => QuestionEntity.fromJson(e))
          .toList();
    }
    return [];
  }

  ///获取问题类型
  static Future<List<QuestionType>> getQuestionType() async {
    final result =
        await DioUtils.post("/${ApiDir.info}/app-help-suggest/helpTypeList");
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return result.data["d"]
          .map<QuestionType>((e) => QuestionType.fromJson(e))
          .toList();
    }
    return [];
  }

  ///反馈提交
  static Future<int?> sendFeedback(
      {String? images, String? suggest, int? type, String? wechat}) async {
    final params = {
      "images": images,
      "suggest": suggest,
      "type": type,
      "wechat": wechat
    };
    final result = await DioUtils.post(
        "/${ApiDir.info}/app-help-suggest/suggest",
        params: params,
        showLoading: true);
    if (result.statusCode == 200) {
      return result.data["c"];
    }
    return null;
  }

  ///获取反馈类型列表
  static Future<List<QuestionType>> getFeedbackType() async {
    final result =
        await DioUtils.post("/${ApiDir.info}/app-help-suggest/suggestTypeList");
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return result.data["d"]
          .map<QuestionType>((e) => QuestionType.fromJson(e))
          .toList();
    }
    return [];
  }

  ///获取反馈记录
  static Future<List<FeedbackEntity>> getFeedbackHistory() async {
    final result =
        await DioUtils.post("/${ApiDir.info}/app-help-suggest/suggestList");
    if (result.statusCode == 200 && result.data["c"] == 200) {
      return result.data["d"]
          .map<FeedbackEntity>((e) => FeedbackEntity.fromJson(e))
          .toList();
    }
    return [];
  }

  ///获取用户头像名字状态
  static Future<UserEditStateEntity> getUserEditState() async {
    try {
      final result =
          await DioUtils.post("/${ApiDir.user}/usr-do/queryUserInfoWithId");
      if (result.statusCode == 200 && result.data["c"] == 200) {
        final data = UserEditStateEntity.fromJson(result.data["d"]);
        return data;
      }
    } catch (e) {
      return UserEditStateEntity();
    }
    return UserEditStateEntity();
  }

  //球队支持
  static Future<int?> supportTeam({int? teamId, int? matchId}) async {
    final params = {
      "interId": matchId,
      "subId": teamId,
      "type": "MATCH_SUPPORT",
    };
    final result =
        await DioUtils.post("/user/add", params: params, showLoading: false);
    if (result.statusCode == 200) {
      return result.data["c"];
    }
    return null;
  }
}
